package com.entertainment.ticketing.controller;

import com.entertainment.ticketing.dto.UserDTO;
import com.entertainment.ticketing.dto.UpdateUserStatusRequest;
import com.entertainment.ticketing.dto.ResetPasswordRequest;
import com.entertainment.ticketing.entity.UserInfo;
import com.entertainment.ticketing.repository.UserInfoRepository;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.crypto.password.PasswordEncoder;

@RestController
@RequestMapping("/api/users")
public class AdminUserController {
    private final UserInfoRepository userRepo;
    private final PasswordEncoder passwordEncoder;

    public AdminUserController(UserInfoRepository userRepo, PasswordEncoder passwordEncoder) {
        this.userRepo = userRepo;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping
    public ResponseEntity<com.entertainment.ticketing.dto.PageResponse<UserDTO>> list(
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "keyword", required = false) String keyword
    ) {
        int safePage = Math.max(0, page);
        int safeSize = Math.min(Math.max(1, size), 100);
        Pageable pageable = PageRequest.of(safePage, safeSize, Sort.by(Sort.Direction.DESC, "createdAt"));

        Page<UserInfo> pageResult = userRepo.searchByKeyword(
                (keyword != null && !keyword.isBlank()) ? keyword.trim() : null,
                pageable
        );

        List<UserDTO> content = pageResult.getContent().stream().map(this::toDTO).collect(Collectors.toList());
        com.entertainment.ticketing.dto.PageResponse<UserDTO> resp = new com.entertainment.ticketing.dto.PageResponse<>(
                content,
                pageResult.getNumber(),
                pageResult.getSize(),
                pageResult.getTotalElements(),
                pageResult.getTotalPages(),
                "createdAt",
                "DESC"
        );
        return ResponseEntity.ok(resp);
    }

    @GetMapping("/{id}")
    public ResponseEntity<UserDTO> detail(@PathVariable Long id) {
        UserInfo u = userRepo.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));
        return ResponseEntity.ok(toDTO(u));
    }

    @PostMapping
    public ResponseEntity<UserDTO> create(@Valid @RequestBody UserDTO dto) {
        UserInfo u = new UserInfo();
        u.setUsername(dto.getUsername());
        u.setEmail(dto.getEmail());
        u.setPhone(dto.getPhone());
        u.setRealName(dto.getRealName());
        u.setAvatarUrl(dto.getAvatarUrl());
        u.setStatus((byte)1);
        u.setRole(dto.getRole() != null ? dto.getRole() : "USER");
        // 为安全起见，创建用户需通过注册接口设置密码；这里仅演示（实际应要求密码）
        u.setPassword("{noop}changeme");
        UserInfo saved = userRepo.save(u);
        return ResponseEntity.ok(toDTO(saved));
    }

    @PutMapping("/{id}")
    public ResponseEntity<UserDTO> update(@PathVariable Long id, @RequestBody UserDTO dto) {
        UserInfo u = userRepo.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));
        if (dto.getUsername() != null) u.setUsername(dto.getUsername());
        if (dto.getEmail() != null) u.setEmail(dto.getEmail());
        if (dto.getPhone() != null) u.setPhone(dto.getPhone());
        if (dto.getRealName() != null) u.setRealName(dto.getRealName());
        if (dto.getAvatarUrl() != null) u.setAvatarUrl(dto.getAvatarUrl());
        if (dto.getRole() != null) u.setRole(dto.getRole());
        UserInfo saved = userRepo.save(u);
        return ResponseEntity.ok(toDTO(saved));
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<UserDTO> updateStatus(@PathVariable Long id, @Valid @RequestBody UpdateUserStatusRequest req) {
        UserInfo u = userRepo.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));
        u.setStatus(req.getStatus());
        UserInfo saved = userRepo.save(u);
        return ResponseEntity.ok(toDTO(saved));
    }

    @PutMapping("/{id}/password")
    public ResponseEntity<Void> resetPassword(@PathVariable Long id, @Valid @RequestBody ResetPasswordRequest req) {
        UserInfo u = userRepo.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));
        u.setPassword(passwordEncoder.encode(req.getNewPassword()));
        userRepo.save(u);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        if (!userRepo.existsById(id)) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在");
        }
        userRepo.deleteById(id);
        return ResponseEntity.ok().build();
    }

    private UserDTO toDTO(UserInfo u) {
        return UserDTO.builder()
                .id(u.getId())
                .username(u.getUsername())
                .email(u.getEmail())
                .phone(u.getPhone())
                .realName(u.getRealName())
                .avatarUrl(u.getAvatarUrl())
                .role(u.getRole())
                .build();
    }
}